package com.lgmshare.component.app;

import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.lgmshare.component.logger.Logger;
import com.lgmshare.component.utils.PermissionCheckUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 框架fragment基类
 * 在onCreateView中处理了View的重复绘制
 *
 * @author: lim
 * @description: 框架fragment类
 * @email: lgmshare@gmail.com
 * @datetime 2014年7月7日  上午11:04:44
 */
public abstract class LaraFragment extends Fragment {

    /**
     * 调试TAG
     */
    protected final String TAG = LaraFragment.this.getClass().getName();

    protected View mRootView;

    /** 集成权限处理*/
    // 系统权限管理页面的参数
    private static final int PERMISSION_REQUEST_CODE = 0x123;
    private PermissionCheckCallback mPermissionCheckCallback;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Logger.v(TAG, "onAttach");
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Logger.v(TAG, "onCreate");
        initData();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Logger.v(TAG, "onCreateView");
        int resId = onBindLayoutResId();
        if (resId > 0) {
            mRootView = inflater.inflate(resId, container, false);
        }
        initView();
        return mRootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Logger.v(TAG, "onActivityCreated");
        initLoad();
    }

    /**
     * 绑定布局资源文件ID
     * use with {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}
     *
     * @return 资源布局文件ID
     */
    protected abstract int onBindLayoutResId();

    /**
     * 初始化Intent Data
     * use with {@link #onCreate(Bundle)}
     */
    protected abstract void initData();

    /**
     * 初始化View
     * use with {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}
     */
    protected abstract void initView();

    /**
     * 初始化数据加载
     * use with {@link #onActivityCreated(Bundle)}
     */
    protected abstract void initLoad();

    @Override
    public void onStart() {
        super.onStart();
        Logger.v(TAG, "onStart");
    }

    @Override
    public void onResume() {
        super.onResume();
        Logger.v(TAG, "onResume");
    }

    @Override
    public void onPause() {
        super.onPause();
        Logger.v(TAG, "onPause");
    }

    @Override
    public void onStop() {
        super.onStop();
        Logger.v(TAG, "onStop");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Logger.v(TAG, "onDestroyView");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Logger.v(TAG, "onDestroy");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        Logger.v(TAG, "onDetach");
    }

    protected <T extends View> T findViewById(@IdRes int id) {
        if (mRootView == null) {
            return null;
        }
        return mRootView.findViewById(id);
    }

    /**
     * 检查功能权限
     *
     * @param permission
     * @return
     */
    protected boolean checkPermission(String permission) {
        return checkPermission(new String[]{permission});
    }

    /**
     * 检查功能权限
     *
     * @param permissions
     * @return
     */
    protected boolean checkPermission(String[] permissions) {
        return PermissionCheckUtils.checkPermission(getActivity(), permissions);
    }

    /**
     * 启动当前权限页面的公开接口
     * targetSdkVersion必须在 >=23，才能返回正确的操作值
     *
     * @param permission         权限
     * @param permissionCallback 权限结果回调
     */
    protected void checkRequestPermission(String permission, PermissionCheckCallback permissionCallback) {
        checkRequestPermissions(new String[]{permission}, permissionCallback);
    }

    /**
     * 启动当前权限页面的公开接口
     * targetSdkVersion必须在 >=23，才能返回正确的操作值
     *
     * @param permissions        权限组
     * @param permissionCallback 权限结果回调
     */
    protected void checkRequestPermissions(String[] permissions, PermissionCheckCallback permissionCallback) {
        boolean result = PermissionCheckUtils.checkPermission(getActivity(), permissions);
        if (result) {
            if (permissionCallback != null) {
                permissionCallback.onPermissionsGranted(permissions);
            }
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                mPermissionCheckCallback = permissionCallback;
                PermissionCheckUtils.requestPermissions(this, permissions, PERMISSION_REQUEST_CODE);
            } else {
                if (permissionCallback != null) {
                    permissionCallback.onPermissionsGranted(permissions);
                }
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            List<String> grantedList = new ArrayList<>();
            List<String> deniedList = new ArrayList<>();
            for (int i = 0; i < permissions.length; i++) {
                String permission = permissions[i];
                if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                    grantedList.add(permission);
                } else {
                    deniedList.add(permission);
                }
            }
            if (permissions.length == grantedList.size()) {
                if (mPermissionCheckCallback != null) {
                    String[] strings = grantedList.toArray(new String[grantedList.size()]);
                    mPermissionCheckCallback.onPermissionsGranted(strings);
                    mPermissionCheckCallback = null;
                }
            } else {
                if (mPermissionCheckCallback != null) {
                    String[] strings = deniedList.toArray(new String[deniedList.size()]);
                    mPermissionCheckCallback.onPermissionDenied(strings);
                    mPermissionCheckCallback = null;
                }
            }
        }
    }

    public interface PermissionCheckCallback {

        void onPermissionsGranted(String[] permissions);

        void onPermissionDenied(String[] permissions);
    }
}
